package mvc.model.inventory

import ext.log
import org.json.JSONObject
import java.lang.Exception
import java.text.ParseException


class WaresInfo(
    val name: String, // 商品名称
    val id: String, // 商品ID
    val price: Double, // 商品价格
    val minImageUrl: String, // 商品图片1
    val maxImageUrl: String, // 商品图片2
    val starValue: Int, // 商品推荐星级
    val description: String, // 商品描述
    val goodsTypes: List<GoodsType>
) // 商品货道位置
{
    companion object {

        fun withEmpty(): WaresInfo {
            return WaresInfo("", "", 0.0, "", "", 0, "", emptyList())
        }

        fun withJson(json: JSONObject): WaresInfo {
            val name = json.getString("WaresName")
            val id = json.getString("WaresId")
            val price = json.getDouble("WaresPrice")
            val url1 = json.getString("WaresImage1")
            val url2 = json.getString("WaresImage2")
            val starValue = json.getInt("StarValue")
            val description = json.getString("WaresDiscr")
            val gts = ArrayList<GoodsType>()
            val arr = json.getJSONArray("GoodsType")
            val length = arr.length()
            for (i in 0 until length) {
                gts.add(GoodsType.withJson(arr.getJSONObject(i)))
            }
            return WaresInfo(name, id, price, url1, url2, starValue, description, gts)
        }
    }

    fun clearByCargo(name: String): Boolean {
        goodsTypes.forEach {
            if (it.name == name) {
                log("${it.name} 无货")
                it.number = 0
                update()
                return true
            }
        }
        return false
    }

    var allNumber: Int = 0
        private set

    init {
        update()
    }

    fun update() {
        var s = 0
        for (g in goodsTypes) {
            if (g.number > 0) {
                s += g.number
            }
        }
        allNumber = s
        log("$name $allNumber")
    }

    fun firstGoodsType(): GoodsType {
        for (g in goodsTypes) {
            log("$name ${g.number}")
            if (g.number > 0) {
                g.number --
                return g
            }
        }
        throw Exception("货道错误")
    }
}

